import { IFeidaoAiBrowserComponent } from '@dfeidao/atom-web/interfaces';
import get from '@dfeidao/atom-web/local/get';
import remove from '@dfeidao/atom-web/local/remove';
import fire from '@dfeidao/atom-web/msg/fire';
import nodejs from "@dfeidao/atom-web/msg/nodejs";
import error from '@dfeidao/atom-web/msgbox/error';
import success from '@dfeidao/atom-web/msgbox/success';
import s_get from '@dfeidao/atom-web/storage/get';
import { md5 } from '@dfeidao/atom-web/str/md5';

interface Aa {
	filename: string;
	metadata: {
		originialFileName: string;
	};
	contentType: string;
}
export default async function a002(fd: IFeidaoAiBrowserComponent) {
	//  保存
	const usercode = fd.data.node.querySelector<HTMLInputElement>('#usercode').value;
	const user_name = fd.data.node.querySelector<HTMLInputElement>('#user_name').value;
	const name_spell = fd.data.node.querySelector<HTMLInputElement>('#name_spell').value;
	const is_disabled = fd.data.node.querySelector<HTMLInputElement>('#is_disabled').value === 'true' ? true : false;
	const email = fd.data.node.querySelector<HTMLInputElement>('#email').value;
	const phone = fd.data.node.querySelector<HTMLInputElement>('#phone').value;
	const create_time = new Date().getTime();
	const password = md5(usercode + '111111');

	const prid = await s_get('productid');
	const head = get(fd, 'res_upload') as Aa;

	let avatar_path;// 路径
	let avatar_name;// 名称
	let avatar_type;// type
	if (!head) {
		avatar_path = "";
		avatar_name = "";
		avatar_type = "";
	} else {
		avatar_path = head.filename;
		avatar_name = head.metadata.originialFileName;
		const contentType = head.contentType;
		const index = contentType.lastIndexOf("/");
		avatar_type = contentType.substring(index + 1, contentType.length);
	}
	if (!usercode) {
		error('用户名不能为空');
		return;
	}
	if (!user_name) {
		error('昵称不能为空');
		return;
	}
	const query1 = {
		filter: {
			usercode
		},
		// productid: prid,
		repeat: 'repeat'
	};
	const res1 = await nodejs<{ dataArray: object[] }>('consumer/zj-000002/s001', query1);
	if (res1.dataArray.length !== 0) {
		error('用户名已存在');
		return;
	}
	const query = {
		usercode,
		user_name,
		name_spell,
		is_disabled,
		create_time,
		productid: prid,
		avatar_path,
		avatar_name,
		avatar_type,
		email,
		phone,
		password,
		last_login_time: 0,
		phone_verified: false,
		email_verified: false,
		is_admin: false
	};
	const res = await nodejs('consumer/zj-000002/s002', query);
	if (res === 'success') {
		fire('zj-000001', 'ec-003');
		fd.data.node.classList.add('display-n');
		remove(fd, 'res_upload');
		success('保存成功');
	} else {
		error('保存失败');
	}
}
